package com.ruoyi.file.util;
import com.ruoyi.file.domain.UserFileInfo;
import org.springframework.web.multipart.MultipartFile;


import javax.activation.MimetypesFileTypeMap;
import java.io.*;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 文件上传处理工具
 * @author zhangxiliang
 * @date 2021/10/16
 */
public class FileUtil {

    /**
     * 生成随机且唯一的文件名
     */
    public static String genFileName(String originalFilename){
        String fileSuffix = ToolUtil.getFileSuffix(originalFilename);
        return UUID.randomUUID().toString().replace("-", "") + fileSuffix;
    }

    /**
     * 生成指定格式的目录名称(日期格式)
     */
    public static String genDateMkdir(String format){
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return "/" + sdf.format(new Date()) + "/";
    }

    /**
     * 获取文件MD5值和SHA1值
     * @param multipartFile FileItemVo对象
     * @param userFileInfo userFileInfo
     */
    public static void transferTo(MultipartFile multipartFile, UserFileInfo userFileInfo) throws IOException, NoSuchAlgorithmException {

        byte[] buffer = new byte[4096];
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        MessageDigest sha1 = MessageDigest.getInstance("SHA1");
        try (InputStream fis = multipartFile.getInputStream()) {
            int len = 0;
            while ((len = fis.read(buffer)) != -1) {

                md5.update(buffer, 0, len);
                sha1.update(buffer, 0, len);
            }
        }
        BigInteger md5Bi = new BigInteger(1, md5.digest());
        BigInteger sha1Bi = new BigInteger(1, sha1.digest());
        userFileInfo.setMd5(md5Bi.toString(16));
        userFileInfo.setSha1(sha1Bi.toString(16));
    }

    /**
     * 通过文件名获取MIME类型
     * @param filename
     */
    public static String getMimeType(String filename) {
        String type = new MimetypesFileTypeMap().getContentType(filename);
        return type;
    }


}
